/**
 * 
 */
package com.vision.core.cl.ui.component;

import java.util.List;

import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent.SelectionChangedHandler;
import com.vision.core.cl.ui.TabItemPanel;

/**
 * @author Mark
 *
 */
public abstract class MultiSelectListAndDetailPanel<T> extends TabItemPanel implements Editor<T> {

	protected void initGridHandlers(final Grid<T> grid) {
//		grid.addCellClickHandler(new CellClickHandler() {
//			@Override
//			public void onCellClick(CellClickEvent event) {
//				int row = event.getRowIndex();
//				int col = event.getCellIndex();
//				// Ignore if the clicked cell is the checkbox cell or if out of bounds
//				if (col == 0 || row < 0 || row >= grid.getStore().size())
//					return;
//				
//				onSelected(grid.getStore().get(row));
//			}
//		});
		
		// Add a listener to the grid
		grid.getSelectionModel().addSelectionChangedHandler(new SelectionChangedHandler<T>() {
			@Override
			public void onSelectionChanged(SelectionChangedEvent<T> event) {
				List<T> selected = event.getSelection();
				if (selected.isEmpty()) return;
				
				// Get the last selected item
				onSelected(selected.get(selected.size() - 1));
			}
		});	
	}
	
	protected void onSelected(final T object) {
		// FIXME getDriver().isDirty() fails if there is currently no object being "editted"
//		if (getDriver().isDirty()) { // If there are unsaved changes in the form
//			UI.confirmUnsavedChanges(
//				new ConfirmDialogHandler() {
//					@Override
//					public void onYes(HideEvent event) {
//						edit(object);
//					}
//				}
//			);
//		} else {
//			edit(object);
//		}
		edit(object);
	}
	
	/**
	 * Loads the <tt>object</tt> into the form editor.
	 * 
	 * @param object
	 */
	protected void edit(final T object) {
		getDriver().edit(object);
	}
	
	protected abstract SimpleBeanEditorDriver<T, ? extends MultiSelectListAndDetailPanel<T>> getDriver();

}
